#include "CIrrlichtWindow.h"

using namespace irr;

CIrrlichtWindow::CIrrlichtWindow(QObject *parent)
	: QObject(parent), Device(NULL), Driver(NULL), SceneManager(NULL), SceneNode(NULL)
{
	/* We first create the Irrlicht device and load a mesh.
	You should understand at least the basics of Irrlicht already, so we will not go into the details here. */
	Device = createDevice(video::EDT_DIRECT3D9, core::dimension2d<u32>(640,480));
	Driver = Device->getVideoDriver();
	SceneManager = Device->getSceneManager();
	Device->setWindowCaption(L"Example 2: Irrlicht Integration (QtPropertyExplorer)");

	// Add a camera
	SceneManager->addCameraSceneNode(0, core::vector3df(0, 55, -75), core::vector3df(0,32,0));

	// Now we load an animated mesh scenenode (you find the dwarf.x in the "media"-directory in the Irrlicht SDK)
	SceneNode = SceneManager->addAnimatedMeshSceneNode(SceneManager->getMesh("dwarf.x"));
	if (SceneNode)
	{
		SceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
		SceneNode->setAnimationSpeed(20);
	}

	/* Note: The above code is very close to the example code posted on the home page of the official Irrlicht documentation.
	This should make it very easy to understand, even for beginners. */
}

CIrrlichtWindow::~CIrrlichtWindow()
{
	Device->closeDevice();
	Device->drop();
}

io::IAttributes *CIrrlichtWindow::createAttributes()
{
	if(!SceneNode || !Device)
		return NULL;

	// Create and fill the attributes
	io::IAttributes* result = Device->getFileSystem()->createEmptyAttributes(Driver);
	SceneNode->serializeAttributes(result);
	return result;
}

void CIrrlichtWindow::onAttributesChangedByEditor(io::IAttributes* attributes)
{
	if(!attributes)
		return;

	SceneNode->deserializeAttributes(attributes);
}

void CIrrlichtWindow::run()
{
	if(Device && Device->run() && Driver && SceneManager)
	{
		Driver->beginScene(true, true, video::SColor(255,112,146,190));
		SceneManager->drawAll();
		Driver->endScene();
	}
}
